package com.cci.kangdao.fieldService.aop;

import com.cci.kangdao.common.type.NotifyChannelType;
import com.cci.kangdao.common.type.NotifyModelType;
import com.cci.kangdao.fieldService.aop.model.CFWOThreadLocal;
import com.cci.kangdao.service.NotifyConfigService;
import com.cci.kangdao.utilTool.NumberUtils;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.RequestContextHolder;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author William Du
 * @date 2020/8/3
 */
@Component
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE + 2)
public class FieldServiceNotifyIntercept {

    private static final Logger logger = Logger.getLogger(FieldServiceNotifyIntercept.class);
    @Resource
    private NotifyConfigService notifyConfigService;

    @Around("execution(* com.cci.kangdao.fieldService.service.*.*(..)))")
    public Object aroundCCG(ProceedingJoinPoint proceedingJoinPoint) {
        try {
            Object response = null;
            response = proceedingJoinPoint.proceed();
            Long orderId = CFWOThreadLocal.get();
            String className = proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName();
            String methodName = proceedingJoinPoint.getSignature().getName();
            if (NumberUtils.isPositiveNum(orderId)) {
                notifyConfigService.doNotify(NotifyChannelType.CBU.getCode(), NotifyModelType.CFWO.getCode(), className, methodName, orderId);
            }
            return response;
        } catch (Throwable throwable) {
            logger.error(throwable.getMessage(), throwable);
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse());
        } finally {
            //清除ThreadLocal值，防止异常线程调用
            CFWOThreadLocal.clear();
        }
        return null;
    }
}
